package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.bo.AdminLoginBO;
import com.cskaoyan.mall.model.sql.Result;
import com.cskaoyan.mall.model.sql.User;
import com.cskaoyan.mall.model.vo.AdminLoginVO;
import com.cskaoyan.mall.model.vo.OrderByStateVO;
import com.cskaoyan.mall.model.vo.UserSignUpVO;
import com.cskaoyan.mall.service.UserService;
import com.cskaoyan.mall.service.implement.UserServiceImpl;
import com.cskaoyan.mall.utils.HttpUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/mall/user/*")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String action = requestURI.replace("/api/mall/user/", "");
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String action = requestURI.replace("/api/mall/user/", "");
        if("signup".equals(action)){
            signup(req,resp);
        }else if ("login".equals(action)){
            login(req,resp);
        }
    }

    /**
     * 登录检测
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtils.getRequestBody(req);
        AdminLoginBO userLogin = gson.fromJson(requestBody, AdminLoginBO.class);
        String nickName = userService.login(userLogin);
        if(nickName==null){
            resp.getWriter().println(gson.toJson(Result.error("用户或者密码错误！---咨询FengFeng")));
            return;
        }
        AdminLoginVO adminLoginVO = new AdminLoginVO();
        adminLoginVO.setName(nickName);adminLoginVO.setToken(nickName);
        resp.getWriter().println(gson.toJson(Result.ok(adminLoginVO)));
    }

    /**
     * 注册用户
     * @param req
     * @param resp
     */
    private void signup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtils.getRequestBody(req);
        User user = gson.fromJson(requestBody,User.class);
        UserSignUpVO userSignUpVO = userService.signup(user);
        resp.getWriter().println(gson.toJson(Result.ok(userSignUpVO)));
    }
}
